<template>
  <div class="personal-center">
    <div class="header">
      <h1>个人中心</h1>
    </div>

    <div class="profile-card" v-if="!isEditing">
      <div class="avatar-section">
        <img :src="user.avatar || defaultAvatar" :alt="user.nickname" class="avatar" />
        <h2>{{ user.nickname || '未设置昵称' }}</h2>
      </div>

      <div class="info-section">
        <div class="info-item">
          <span class="label">手机号:</span>
          <span class="value">{{ user.phone }}</span>
        </div>

        <div class="info-item">
          <span class="label">性别:</span>
          <span class="value">{{ genderMap[user.gender] }}</span>
        </div>
        <div class="info-item">
          <span class="label">账号状态:</span>
          <span class="value" :class="user.status === 1 ? 'active' : 'inactive'">
            {{ statusMap[user.status] }}
          </span>
        </div>

        <div class="info-item">
          <span class="label">角色:</span>
          <span class="value">{{ roleMap[user.role] }}</span>
        </div>
      </div>

      <div class="action-section">
        <button class="edit-btn" @click="startEdit">编辑资料</button>
      </div>
    </div>

    <!-- 编辑表单 -->
    <div class="profile-card" v-else>
      <div class="edit-form">
        <div class="form-group">
          <label>头像:</label>
          <div class="avatar-upload">
            <img :src="editForm.avatar || previewAvatar || defaultAvatar" :alt="user.nickname" class="avatar-preview" />
            <input type="file" ref="avatarInput" accept="image/*" @change="handleAvatarChange" style="display: none" />
            <button type="button" @click="triggerAvatarUpload" class="upload-btn">
              {{ editForm.avatar || previewAvatar ? '更换头像' : '上传头像' }}
            </button>
          </div>
        </div>
        <div class="form-group">
          <label>昵称:</label>
          <input v-model="editForm.nickname" type="text" placeholder="请输入昵称" />
        </div>

        <div class="form-group">
          <label>性别:</label>
          <select v-model="editForm.gender">
            <option :value="0">未知</option>
            <option :value="1">男</option>
            <option :value="2">女</option>
          </select>
        </div>
        <div class="form-actions">
          <button class="cancel-btn" @click="cancelEdit">取消</button>
          <button class="save-btn" @click="saveProfile">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserInfo, uploadAvatar,updateUserInfo } from '@/apis/userAPI'

// 用户数据
const user = ref({
  id: '',
  phone: '',
  status: 1,
  role: 1,
  gender: 0,
  nickname: '',
  avatar: '',
})

// 编辑状态
const isEditing = ref(false)

// 编辑表单数据
const editForm = ref({
  nickname: '',
  gender: 0,
  birthday: '',
  region: ''
})
// 头像预览
const previewAvatar = ref('')
// 文件输入引用
const avatarInput = ref(null)
// 状态映射
const statusMap = {
  0: '禁用',
  1: '启用'
}

const roleMap = {
  0: '管理员',
  1: '用户'
}

const genderMap = {
  0: '未知',
  1: '男',
  2: '女'
}

// 默认头像
const defaultAvatar = 'https://via.placeholder.com/100x100?text=头像'

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
  // 初始化编辑表单数据
  editForm.value = {
    avatar: user.value.avatar || '',
    nickname: user.value.nickname || '',
    gender: user.value.gender,
    birthday: user.value.birthday || '',
    region: user.value.region || ''
  }
  previewAvatar.value = ''
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  previewAvatar.value = ''
}


// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value.click()
}

// 处理头像更改
// 上传文件的正确方式
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (file) {
    try {
      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', file) // 'file' 是后端接收的字段名
      
      // 调用上传接口
      const result = await uploadAvatar(formData)
      
      // 假设后端返回格式为 { code: 200, data: { url: '图片地址' } }
      if (result.data) {
        editForm.value.avatar = result.data
        previewAvatar.value = result.data
        console.log('头像上传成功:', result.data)
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      // 处理错误，如显示错误提示
    }
  }
}


// 保存资料
const saveProfile = async () => {
  // 这里应该调用API保存用户信息
  // 示例代码：
  user.value.nickname = editForm.value.nickname
  user.value.gender = editForm.value.gender
  user.value.birthday = editForm.value.birthday
  user.value.region = editForm.value.region


  // 如果有新头像，则更新头像
  if (previewAvatar.value) {
    user.value.avatar = previewAvatar.value
  } else if (editForm.value.avatar) {
    user.value.avatar = editForm.value.avatar
  }
  console.log('保存用户信息:', editForm.value)
  const result = await updateUserInfo(editForm.value)
  if (result.code === 1) {
    // 保存成功后关闭编辑状态
    isEditing.value = false
  } else {
    ElMessage.error('保存失败')
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  // 这里应该调用API获取用户信息
  const result = await getUserInfo()
  user.value = result.data

}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.personal-center {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.header h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.profile-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 15px;
  border: 3px solid #f0f0f0;
}

.avatar-section h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.info-section {
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: bold;
  color: #666;
  flex: 1;
}

.value {
  flex: 1;
  text-align: right;
  color: #333;
}

.value.active {
  color: #4caf50;
}

.value.inactive {
  color: #f44336;
}

.action-section {
  text-align: center;
}

.edit-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.edit-btn:hover {
  background-color: #337ecc;
}

/* 编辑表单样式 */
.edit-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  border-color: #409eff;
  outline: none;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.cancel-btn,
.save-btn {
  padding: 10px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn {
  background-color: #ccc;
  color: #333;
}

.cancel-btn:hover {
  background-color: #999;
}

.save-btn {
  background-color: #409eff;
  color: white;
}

.save-btn:hover {
  background-color: #337ecc;
}

/* 头像上传样式 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.upload-btn {
  background-color: #67c23a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.upload-btn:hover {
  background-color: #5daf34;
}
</style>